package com.cn.wanxi.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 经常使用的工具类，最好不要让别人轻易创建对象
 */
public class IOTool {
    //    private static final String SPLIT = "\n";
//    private static String DIRECTORY = "note";
    private static File FILE = null;

    private IOTool() {
    }

    private static File createNote(String path, String fileName) {
        File dir = new File(path, Path.DIRECTORY);
        dir.mkdirs();
        File file = new File(dir, fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    public static void writeNote(List<String> data, String path, String fileName) {
        FILE = createNote(path, fileName);
        try {
            OutputStream outputStream = new FileOutputStream(FILE);
            for (int i = 0; i < data.size(); i++) {
                outputStream.write(data.get(i).getBytes(StandardCharsets.UTF_8));
                outputStream.write(Path.SPLIT.getBytes(StandardCharsets.UTF_8));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static String readNote() {
        StringBuilder result = new StringBuilder();
        try {
//            字节流InputStream 中文能不能用字节流？
//            一个中文有多少个字节？
//            String aa="中";
//            System.out.println(aa.getBytes("GBK").length);
//            InputStream inputStream=new FileInputStream(file);
//            int read = 0;
//            while (read!=-1){
//                read = inputStream.read();
//                char t= (char) read;
//                System.out.print(t);
//            }
//            字符流

//            Reader reader = new FileReader(file);
            InputStream inputStream = new FileInputStream(FILE);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
//Reader aa=new FileReader(file);
//            為什麼这里会直接转换为StringBuilder？
//            String和StringBuilder和StringBuffer的区别？

//            String result = "";
            int read = 0;
//            int a=0;
//            byte b=0;
//            b+=a;//自动转型
//            b= (byte)(a + b);
            while ((read = reader.read()) != -1) {
//                read = reader.read();
                result.append((char) read);
//                System.out.print((char) read);
            }
//            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

}
